$m(function() {
    var that = this;
    var $this = this.element;

    /**
     * 页面
     */
    var page = $("#tempo-mine-sample-code");

    /**
     * 角色信息表格
     */
    var grid = $("#tempo-mine-sample-code-grid");

    /**
     * 初始化
     */
    var init = function(){
        initLayout();
        renderGrid();

    };

    /**
     * 初始化布局
     */
    var initLayout = function(){
        page.layout({
            north : {
                resizable : false,
                size : 45,
                spacing_open : 0,
                closable : false
            },
            center:{
                onresize:TempoUtils.throttle(function(){
                    grid.datagrid("resize");
                },200,true)
            }
        });
    };


    /**
     * 搜索框事件处理
     */
    var searchHandle = function(text){
        grid.datagrid("reloadGrid",{
            text :　text
        },false);
    }

    /**
     * 创建工具栏的配置数组
     * */
    var createToolBarConfig = function() {
        var arr = [[TempoUtils.locale("mine.xinzeng"),'add','',addQueue]];
        var tbConfig = [];
        $.each(arr, function(i, item) {
            tbConfig.push({
                id : "sample_btn_" + item[1],
                text : item[0],
                icon : item[2],
                click : item[3]
            });
        });
        return tbConfig;
    }

    /**
     * 绘制列表
     */
    var renderGrid = function(){
        grid.datagrid({
            url:contextPath +"/api/ai/sysconfig/samplecode/listAllSampleCode",
            datatype:'json',
            fit:true,
            rownumbers : true,
            separator:false,
            loadui:'disable',
            colNames:[
                'id',
                TempoUtils.locale("mine.sampleCodeName"),
                TempoUtils.locale("mine.sampleCodeType"),
                TempoUtils.locale("mine.sampleCodeAuthor"),
                TempoUtils.locale("mine.sampleCodeCreateTime"),
                TempoUtils.locale("mine.action")],
            toolbar : createToolBarConfig(),
            colModel:[{
                name:'ID',
                sortable:false,
                hidden : true
            },{
                name:'NAME',
                sortable:false,
                align : 'center',
                formatter : function(obj, grid, rows, state) {
                    return TempoMineUtils.encodeHTML(obj);
                }
            },{
                name:'TYPE',
                sortable:false,
                align : 'center',
                formatter: function(value, row, rowData) {
                    if (value == "pythonparallelization") {
                        return "Python分布式";
                    } else {
                        return value;
                    }
                }
            },{
                name:'AUTHOR',
                sortable:false,
                align : 'center'
            },{
                name:'CREATETIME',
                sortable:false,
                align : 'center',
                formatter : function(obj, grid, rows, state) {
                    if(obj){
                        return DateUtils.formatDate(new Date(obj), "yyyy-MM-dd HH:mm:ss");
                    }
                    return;
                }
            },{
                name:'ACTION',
                sortable:false,
                buttons:[{
                    id:"edit",
                    title:"编辑",
                    icon:"ui-icon tempo-ui-icon tempo-ui-icon-edit",
                    click:function(e,et){
                        updateQueue("","编辑",et.rowData);
                    }
                },{
                    id:"delete",
                    title:TempoUtils.locale("mine.delete"),
                    icon:"ui-icon tempo-ui-icon tempo-ui-icon-trash",
                    click:function(e,dt){
                        removesampleCode(dt.rowData);
                    }
                }]
            }],
            pagination:true,
            postData:{
                text :　""
            },
            searchBar:true,
            searchBarOptions:{
                useRadius:false,
                placeholder:TempoUtils.locale("mine.sampleCodeSearch"),
                width:210,
                onSearch:function(text){
                    searchHandle($.trim(text));
                }
            },
        });
    }
    /**
     * 判断textarea中文本类型
     *
     **/

    /**
     * 删除示例
     * @param data
     */
    function removesampleCode(data){
        var deleteDialog = $('<div style="width:100%;height:100%;background-color: #ffffff"/></div>').appendTo($('body'));
        deleteDialog.dialog({
            modal : true,
            width : 420,
            height : 118,
            title : TempoUtils.locale("mine.prompt"),
            resizable : false,
            closeOnEscape : true,
            close:function(){
                deleteDialog.remove();
            },
            open : function(){
                $('<div  class="tempo-sys-delete-dialog-content">'+TempoUtils.locale("mine.querenshanchu")+'</div>').appendTo($(deleteDialog));
            },
            buttons:[{
                text:TempoUtils.locale("mine.publish-dialog-sure"),
                id: 'tempo-sys-ok-btn',
                click:function(){
                    var process = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url:contextPath+"/api/ai/sysconfig/samplecode/deleteSampleCode",
                        data:{
                            id: data.ID,
                        },
                        type:'post',
                        success:function(result){
                            process.tempoprogressbar('destroy');
                            deleteDialog.dialog("close");
                            if(result){
                                grid.trigger("reloadGrid");
                            }else{
                                $("<div/>").alert({
                                    title: TempoUtils.locale("mine.tooltip"),
                                    msg: TempoUtils.locale("sysheader.shanchushibai"),
                                });
                            }
                        }
                    });
                }
            },{
                text:TempoUtils.locale("mine.publish-dialog-cancel"),
                id: 'tempo-sys-cancel-btn',
                click:function(){
                    deleteDialog.dialog("close");
                }
            }]
        })
    }
    /**
     * 新增弹框
     */
    var addQueue = function(event, textTitle, data){
        if(!textTitle){
            textTitle = "新增"
        }
        var dialog = $("<div/>", {
            'class' : 'tempo-sample-code-dialog'
        });
        dialog.dialog({
            modal : true,
            width : 640,
            height : 550,
            resizable : false,
            title : textTitle+'示例代码',
            open:function(){
                $m.loadHtmlSyn(contextPath+"/api/ai/sysconfig/samplecode/view", dialog);
            },
            buttons : [ {
                text : '保存',
                id:'tempo_samplecode_save_btn',
                click : function() {
                    var $dom = $('#dialogSample-tempo').find('form');
                    var record = TempoUtils.getRecord($dom);
                    var success = $dom.formValidate();
                    if(!success) {
                        return;
                    }
                    if(!record.sampleCode.trim()){
                        $('#tipText').css("display","block");
                        $('#sampleCode').addClass('bgRed')
                        $('#sampleCode').focus(function(){
                            $('#tipText').css("display","none");
                            $('#sampleCode').removeClass('bgRed');
                        });
                        return;
                    }else{
                        $('#tipText').css("display","none");
                        $('#sampleCode').removeClass('bgRed');
                    }
                    record.sampleCode = record.sampleCode.trim();
                    $.ajax({
                        url: contextPath + '/api/ai/sysconfig/samplecode/saveSampleCode',
                        method: 'POST',
                        data: record,
                        success: function(result) {
                            if(result.success){
                                grid.datagrid("reloadGrid");
                                dialog.dialog("destroy").remove();
                            }else{
                                $("<div/>").alert({
                                    msg : result.message,
                                    title : TempoUtils.locale("mine.prompt")
                                });
                            }

                        }
                    });
                }
            },{
                text : '取消',
                id:'tempo_samplecode_reset_btn',
                click : function() {
                    dialog.dialog("destroy").remove();
                }
            } ],
            close : function() {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });

    };

    /**
     * 修改
     */
    var updateQueue = function(event, textTitle, data){
        var dialog = $("<div/>", {
            'class' : 'tempo-sample-code-dialog'
        });
        dialog.dialog({
            modal : true,
            width : 640,
            height : 550,
            resizable : false,
            title : textTitle+'示例代码',
            open:function(){
                $m.loadHtml(contextPath+"/api/ai/sysconfig/samplecode/view", dialog, "",data);
            },
            buttons : [ {
                text : '保存',
                id:'tempo_samplecode_save_btn',
                click : function() {
                    var $dom = $('#dialogSample-tempo').find('form');
                    var record = TempoUtils.getRecord($dom);
                    TempoUtils.parserUi($dom, {});
                    var success = $dom.formValidate();
                    if(!success) {
                        return;
                    }
                    record.type = data.TYPE;
                    if(!record.sampleCode){
                        $('#tipText').css("display","block");
                        $('#sampleCode').addClass('bgRed')
                        $('#sampleCode').focus(function(){
                            $('#tipText').css("display","none");
                            $('#sampleCode').removeClass('bgRed');
                        });
                        return;
                    }else{
                        $('#tipText').css("display","none");
                        $('#sampleCode').removeClass('bgRed');
                    }
                    record.oldName = data.NAME;
                    record.sampleCode = record.sampleCode.trim();
                    $.ajax({
                        url: contextPath + '/api/ai/sysconfig/samplecode/updateSampleCodeById',
                        method: 'POST',
                        data: record,
                        success: function(rs) {
                            if(rs.success){
                                grid.datagrid("reloadGrid");
                                dialog.dialog("destroy").remove();
                            }else{
                                $("<div/>").alert({
                                    msg : rs.message,
                                    title : TempoUtils.locale("mine.prompt")
                                });
                            }
                        },
                        error:function(){
                            dialog.dialog("destroy").remove();
                        }
                    });
                }
            },{
                text : '取消',
                id:'tempo_samplecode_reset_btn',
                click : function() {
                    dialog.dialog("destroy").remove();
                }
            } ],
            close : function() {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });

    }

    init();
});